require('./menu');
import Updater from './update';
import getRenderUrl from './mainUrl';
import deviceid from './utils/deviceid.js';
import handleQuit from './event/quit';
import handleMessage from './event/message';
import onCrashed from './protect/crashed';
import createTray from './protect/tray';
import autoStart from './protect/autoStart';
import moment from 'moment';

const Tesseract = require('tesseract.js');
const { app, BrowserWindow, ipcMain } = require('electron');
const request = require('request');
const { exec} = require('child_process');
const fs = require('fs');
const path = require('path');

function callCommandLine(command) {
  exec(command, (error, stdout, stderr) => {
    if (error) {
      console.error(`cmd 执行的错误: ${error}`);
      return;
    }
    console.log(`cmd stdout: ${stdout}`);
    if (stderr) {
      console.error(`cmd stderr: ${stderr}`);
    }
  });
}

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      webSecurity: false,
      nodeIntegration: true,
    },
    // transparent: true,
    titleBarStyle: 'hidden',
    // frame: false
  });
  mainWindow.setAutoHideMenuBar(true)
  mainWindow.loadURL(getRenderUrl());
  if (process.platform === 'win32') {
    mainWindow.on('close', (event) => {
      mainWindow.hide();
      mainWindow.setSkipTaskbar(true);
      event.preventDefault();
    });
  }
  global.mainId = mainWindow.id;

  setInterval(() => {
    const preData = fs.readFileSync(path.join(__dirname, 'db/onlineTime'), 'utf-8');

    const historyOnlineTime = JSON.parse(preData);
    const today = moment().format("YYYY-MM-DD");
    let preLong = historyOnlineTime[moment().format("YYYY-MM-DD")];
    if (preLong == null) {
      preLong = 0;
    }
    historyOnlineTime[today] = preLong+1;
    fs.writeFile(path.join(__dirname, 'db/onlineTime'), JSON.stringify(historyOnlineTime), (err) => {
      if (err) {
        console.error(err);
      }
    });
  }, 60*1000); // 统计使用软件时长

  ipcMain.on('record-historyArticleSubmit',(event) => {
    const preData = fs.readFileSync(path.join(__dirname, 'db/articleSubmit'), 'utf-8');

    const historyarticleSubmit = JSON.parse(preData);
    const today = moment().format("YYYY-MM-DD");
    let preLong = historyarticleSubmit[moment().format("YYYY-MM-DD")];
    if (preLong == null) {
      preLong = 0;
    }
    historyarticleSubmit[today] = preLong+1;
    fs.writeFile(path.join(__dirname, 'db/articleSubmit'), JSON.stringify(historyarticleSubmit), (err) => {
      if (err) {
        console.error(err);
      }
    });
  });

  ipcMain.on('request-ocr',(event, filepath) => {
    Tesseract.recognize(filepath, 'eng', {
      langPath: path.join(__dirname, '..', 'node_modules/@tesseract.js-data/eng/4.0.0_best_int/')
    }).then((d)=>{
      event.sender.send('request-ocr-reply', d.data.text);
    }).catch((err)=>{
      event.sender.send('request-ocr-reply', err);
    });
  });

  ipcMain.on('query-historyOnlineTime',(event) => {
    fs.readFile(path.join(__dirname, 'db/onlineTime'), 'utf-8', (err, data) => {
      if(!err && data) {
        const historyOnlineTime = JSON.parse(data);
        event.sender.send('query-historyOnlineTime-reply', historyOnlineTime);
      }
    });
  });

  ipcMain.on('query-historyArticleSubmit',(event) => {
    fs.readFile(path.join(__dirname, 'db/articleSubmit'), 'utf-8', (err, data) => {
      if(!err && data) {
        const historyOnlineTime = JSON.parse(data);
        event.sender.send('query-historyArticleSubmit-reply', historyOnlineTime);
      }
    });
  });


  ipcMain.on('request-model', (event, params) => {
    const modelUrl = 'http://localhost:11434/api/generate';
    new Promise((resolve, reject) => {
      request.post({url:modelUrl, form:JSON.stringify(params)}, (err, response, body) => {
        Updater.CHECKING = false;
        if (err) {
          return reject(new Error('网络异常，请稍后再试'));
        }
        try {
          const res = JSON.parse(body);
          return resolve(res);
        } catch (error) {
          console.log(error);
          return reject(new Error('异常'));
        }
      });
    }).then((data) => {
      event.sender.send(params['replyKey'], data);
    }).catch((e) => {
      console.log(e)
    });
  });

  ipcMain.on('read-local-file',(event, filePath) => {
    fs.readFile(path.join(__dirname, 'db/'+filePath), 'utf-8', (err, data) => {
      if (err) {
        event.sender.send('read-local-file-reply', '[]');
        return;
      }
      event.sender.send('read-local-file-reply', data);
    });
  });

  ipcMain.on('save-local-file',(event, filePath, content) => {
    fs.writeFile(path.join(__dirname, 'db/'+filePath), content, (err) => {
      if (err) {
        console.error(err);
        event.sender.send('save-local-file', false);
        return;
      }
      event.sender.send('save-local-file', true);
    });
  });
}

// if (process.platform === 'win32') {
//   const shouldQuit = app.makeSingleInstance((commandLine, workingDirectory) => {
//     if (mainWindow) {
//       if (mainWindow.isMinimized()) mainWindow.restore()
//       mainWindow.focus()
//     }
//   })
//   if (shouldQuit) {
//     app.quit()
//   };
// }

const gotTheLock = app.requestSingleInstanceLock()
 
if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 当运行第二个实例时,将会聚焦到myWindow这个窗口
    if (myWindow) {
      if (myWindow.isMinimized()) myWindow.restore()
      myWindow.focus()
    }
  })
}

// const devicePromise = deviceid.get();
app.on('ready', () => {
  // 调用命令行
  callCommandLine('cd Ollama && ollama.exe list');
  createWindow();
  // devicePromise
  //   // .then(() => Updater.init())
  //   .then(() => createWindow())
  //   .then(() => handleMessage())
  //   .then(() => onCrashed())
  //   .then(() => handleQuit())
  //   .then(() => createTray())
  //   .then(() => { if (process.platform === 'win32') { autoStart() } })
})

app.on('activate', function () {
  if (mainWindow === null) {
    createWindow()
  }
});